package edu.fourtwelve.client;

import edu.fourtwelve.Data.DBConstants;
import edu.fourtwelve.srlzd_data.AccountData;
import edu.fourtwelve.srlzd_data.Transaction;
import edu.fourtwelve.util.BankingException;
import edu.fourtwelve.util.RequestType;
import java.awt.event.ItemEvent;
import java.io.IOException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SealedObject;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import javax.swing.table.TableModel;

/**
 *
 * @author Christopher C. Hunt
 */
public class ClientAccounts extends javax.swing.JFrame {

    /**
     * Creates new form ClientAcounts
     */
    public ClientAccounts() {
        initComponents();
    }

    /**
     * Creates new form ClientAcounts
     */
    public ClientAccounts(ClientLogin cLogIn, java.net.Socket socket,
            java.io.ObjectInputStream objInStream, java.io.ObjectOutputStream objOutStream,
            final Cipher cipher, final Cipher decipher) throws BankingException {

        this.cLogIn = cLogIn;
        this.socket = socket;
        this.objInStream = objInStream;
        this.objOutStream = objOutStream;
        this.cipher = cipher;
        this.decipher = decipher;

        try {

            SealedObject sealedAcctsData = (SealedObject) this.objInStream.readObject();
            this.accountsData = (ArrayList<AccountData>) sealedAcctsData.getObject(this.decipher);

        } catch (IOException e) {
            throw new BankingException("Failed to get Object from input stream ", e);
        } catch (ClassNotFoundException e) {
            throw new BankingException("Failed to get Object from input stream ", e);
        } catch (IllegalBlockSizeException e) {
            throw new BankingException("Crypto Failure ", e);
        } catch (BadPaddingException e) {
            throw new BankingException("Crypto Failure ", e);
        }

        if (this.accountsData == null) {
            this.accountsData = new ArrayList<AccountData>();
        }

        initComponents();

        try {
            initAccountData(0);
        } catch (BankingException e) {
            log.log(Level.WARNING, "Faied to initialize AccountsData ", e);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        clientJTabbedPane = new javax.swing.JTabbedPane();
        accountsJScrollPane = new javax.swing.JScrollPane();
        jPanel1 = new javax.swing.JPanel();
        accountNameJComboBox = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        transactionsJTable = new javax.swing.JTable();
        optionsJScrollPane = new javax.swing.JScrollPane();
        jPanel2 = new javax.swing.JPanel();
        transactionTypesComboBox = new javax.swing.JComboBox();
        fromAccountJComboBox = new javax.swing.JComboBox();
        toAccountJComboBox = new javax.swing.JComboBox();
        transactionAmountJTextField = new javax.swing.JTextField();
        transactionAmountJLabel = new javax.swing.JLabel();
        confirmTransactionJButton = new javax.swing.JButton();
        jProgressBar1 = new javax.swing.JProgressBar();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setPreferredSize(new java.awt.Dimension(815, 675));
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                handleClosing(evt);
            }
        });

        clientJTabbedPane.setPreferredSize(new java.awt.Dimension(800, 600));
        clientJTabbedPane.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                tabChangeListener(evt);
            }
        });

        accountsJScrollPane.setPreferredSize(new java.awt.Dimension(800, 600));

        jPanel1.setPreferredSize(new java.awt.Dimension(800, 600));

        accountNameJComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        accountNameJComboBox.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                accountNameJComboBoxItemChanged(evt);
            }
        });

        jScrollPane1.setPreferredSize(new java.awt.Dimension(800, 600));

        transactionsJTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null}
            },
            new String [] {
                "Transaction Description", "Withdrawl", "Deposit", "Balance"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.Integer.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        transactionsJTable.setPreferredSize(new java.awt.Dimension(700, 510));
        transactionsJTable.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(transactionsJTable);
        transactionsJTable.getColumnModel().getColumn(0).setResizable(false);
        transactionsJTable.getColumnModel().getColumn(1).setResizable(false);
        transactionsJTable.getColumnModel().getColumn(2).setResizable(false);
        transactionsJTable.getColumnModel().getColumn(3).setResizable(false);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 758, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(accountNameJComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(30, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(accountNameJComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 540, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(21, Short.MAX_VALUE))
        );

        accountsJScrollPane.setViewportView(jPanel1);
        jPanel1.getAccessibleContext().setAccessibleName("");

        clientJTabbedPane.addTab("Accounts", null, accountsJScrollPane, "");
        accountsJScrollPane.getAccessibleContext().setAccessibleName("Accounts");

        optionsJScrollPane.setPreferredSize(new java.awt.Dimension(800, 600));

        jPanel2.setPreferredSize(new java.awt.Dimension(800, 600));

        transactionTypesComboBox.setModel(new javax.swing.DefaultComboBoxModel(new Object[] { MakeObj("Transaction Options..."), MakeObj("Deposit"), MakeObj("Withdrawl"), MakeObj("Transfer")}));
        transactionTypesComboBox.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                transactionTypeJComboBoxItemChanged(evt);
            }
        });

        fromAccountJComboBox.setModel(new javax.swing.DefaultComboBoxModel(new Object[] { MakeObj("From Account...")}));
        fromAccountJComboBox.setEnabled(false);

        toAccountJComboBox.setModel(new javax.swing.DefaultComboBoxModel(new Object[] { MakeObj("To Account...")}));
        toAccountJComboBox.setEnabled(false);

        transactionAmountJLabel.setText("Transaction Amount:");

        confirmTransactionJButton.setText("Confirm Transaction");
        confirmTransactionJButton.setEnabled(false);
        confirmTransactionJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                confirmTransactionJButtonActionPerformed(evt);
            }
        });

        jProgressBar1.setIndeterminate(true);

        this.jProgressBar1.setVisible(false);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(106, 106, 106)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(confirmTransactionJButton)
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(transactionAmountJLabel)
                                .addGap(18, 18, 18)
                                .addComponent(transactionAmountJTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(toAccountJComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 410, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(transactionTypesComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 253, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(fromAccountJComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 410, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(235, 235, 235)
                        .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 360, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(213, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(121, 121, 121)
                .addComponent(transactionTypesComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(fromAccountJComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(toAccountJComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(transactionAmountJTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(transactionAmountJLabel))
                .addGap(52, 52, 52)
                .addComponent(confirmTransactionJButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 133, Short.MAX_VALUE)
                .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(96, 96, 96))
        );

        for (AccountData cur : this.accountsData) {
            this.fromAccountJComboBox.addItem(MakeObj("From Account - " + cur.getAccountType() + " #"
                + String.valueOf(cur.getAccountNum())));
    }
    for (AccountData cur : this.accountsData) {
        this.toAccountJComboBox.addItem(MakeObj("To Account - " + cur.getAccountType() + " #"
            + String.valueOf(cur.getAccountNum())));
    }

    optionsJScrollPane.setViewportView(jPanel2);

    clientJTabbedPane.addTab("Transfers", optionsJScrollPane);
    optionsJScrollPane.getAccessibleContext().setAccessibleName("Options");

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(clientJTabbedPane, javax.swing.GroupLayout.PREFERRED_SIZE, 815, javax.swing.GroupLayout.PREFERRED_SIZE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addComponent(clientJTabbedPane, javax.swing.GroupLayout.PREFERRED_SIZE, 650, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(0, 0, Short.MAX_VALUE))
    );

    clientJTabbedPane.getAccessibleContext().setAccessibleName("");

    pack();
    }// </editor-fold>//GEN-END:initComponents

    private void handleClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_handleClosing
       this.cLogIn.setVisible(true);
    }//GEN-LAST:event_handleClosing

    private void accountNameJComboBoxItemChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_accountNameJComboBoxItemChanged
        if (evt.getStateChange() == ItemEvent.SELECTED) {
            this.curAcctDisplayed = this.accountsData.get(this.accountNameJComboBox.getSelectedIndex());
            loadTable();
        }
    }//GEN-LAST:event_accountNameJComboBoxItemChanged

    private void tabChangeListener(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_tabChangeListener
       
        if (this.transactionTypesComboBox != null
                && this.fromAccountJComboBox != null
                && this.toAccountJComboBox != null
                && this.confirmTransactionJButton != null) {
            if (this.transactionTypesComboBox.getItemCount() > 0) {
                this.transactionTypesComboBox.setSelectedIndex(0);
                this.fromAccountJComboBox.setEnabled(false);
                this.toAccountJComboBox.setEnabled(false);
                this.confirmTransactionJButton.setEnabled(false);

                if (ClientAccounts.needsDataReload) {
                    SwingWorker<Void, Void> reloadData = new SwingWorker<Void, Void>() {

                        @Override
                        protected Void doInBackground() throws Exception {
                            objOutStream.writeObject(RequestType.GET_ACCOUNT_DATA);
                            objOutStream.flush();

                            SealedObject sealedAcctsData = (SealedObject) objInStream.readObject();
                            accountsData = (ArrayList<AccountData>) sealedAcctsData.getObject(decipher);
                            needsDataReload = false;
                            return null;
                        }

                        @Override
                        public void done() {
                            try {
                                initAccountData(accountNameJComboBox.getSelectedIndex());
                            } catch (BankingException e) {
                                log.log(Level.WARNING, "Faied to initialize AccountsData ", e);
                            }
                        }
                    };
                    reloadData.execute();
                }
            }
        }
    }//GEN-LAST:event_tabChangeListener

    private void confirmTransactionJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_confirmTransactionJButtonActionPerformed
        if (this.transactionAmountJTextField.getText() != null
                && !this.transactionAmountJTextField.getText().equalsIgnoreCase("")) {
            final ClientAccounts thisJFrame = this;
            try {
                switch (TransactionType.get(
                        this.transactionTypesComboBox.getSelectedIndex())) {
                    case DEPOSIT:
                        if (this.toAccountJComboBox.getSelectedIndex() > 0 &&
                                Double.parseDouble(transactionAmountJTextField.getText()) > 0) {
                            this.objOutStream.writeObject(RequestType.DEPOSIT);
                            this.objOutStream.flush();
                            SwingWorker<Void, Void> reloadData = new SwingWorker<Void, Void>() {

                                private boolean success = false;

                                @Override
                                protected Void doInBackground() throws Exception {
                                    jProgressBar1.setVisible(true);
                                    int transTypeId = -1;
                                    String transDescription = "";
                                    if (toAccountJComboBox.getSelectedItem().toString().contains("Checking")) {
                                        transTypeId = DBConstants.CHECKING_CREDIT;
                                        transDescription = "Checking Credit";
                                    } else if (toAccountJComboBox.getSelectedItem().toString().
                                            contains("Savings")) {
                                        transTypeId = DBConstants.SAVINGS_CREDIT;
                                        transDescription = "Savings Credit";
                                    } else if (toAccountJComboBox.getSelectedItem().toString().
                                            contains("Loan")) {
                                        transTypeId = DBConstants.LOAN_CREDIT;
                                        transDescription = "Loan Credit";
                                    }
                                    String[] temp = toAccountJComboBox.getSelectedItem().toString().split(" ");
                                    SealedObject sealedAcctsData = new SealedObject(
                                            new Transaction(0, transTypeId, transDescription,
                                            "Test Transaction", Double.parseDouble(
                                            transactionAmountJTextField.getText()),
                                            Long.parseLong(temp[temp.length - 1].substring(1))), cipher);
                                    objOutStream.writeObject(sealedAcctsData);
                                    objOutStream.flush();

                                    SealedObject seleadSuccess = (SealedObject) objInStream.readObject();
                                    success = (Boolean) seleadSuccess.getObject(decipher);
                                    return null;
                                }

                                @Override
                                public void done() {
                                    jProgressBar1.setVisible(false);
                                    if (success) {
                                        JOptionPane.showMessageDialog(thisJFrame,
                                                "Transaction Successful",
                                                "Success",
                                                JOptionPane.INFORMATION_MESSAGE);
                                        needsDataReload = true;
                                    } else {
                                        JOptionPane.showMessageDialog(thisJFrame,
                                                "Transaction Failure",
                                                "Failure",
                                                JOptionPane.ERROR_MESSAGE);
                                    }
                                }
                            };
                            reloadData.execute();
                        } else {
                            JOptionPane.showMessageDialog(thisJFrame,
                                    "Transaction Failure",
                                    "Failure",
                                    JOptionPane.ERROR_MESSAGE);
                        }
                        break;
                    case WITHDRAWL:
                        if (this.fromAccountJComboBox.getSelectedIndex() > 0 &&
                                Double.parseDouble(transactionAmountJTextField.getText()) > 0) {
                            final String[] temp = fromAccountJComboBox.getSelectedItem().toString().split(" ");
                            AccountData fromAccount = 
                                    this.accountsData.get(this.fromAccountJComboBox.getSelectedIndex()-1);
                            if (Double.parseDouble(transactionAmountJTextField.getText())
                                    < fromAccount.getBalance()) {
                                this.objOutStream.writeObject(RequestType.WITHDRAWL);
                                this.objOutStream.flush();
                                SwingWorker<Void, Void> reloadData1 = new SwingWorker<Void, Void>() {

                                    private boolean success = false;

                                    @Override
                                    protected Void doInBackground() throws Exception {
                                        jProgressBar1.setVisible(true);
                                        int transTypeId = -1;
                                        String transDescription = "";
                                        if (fromAccountJComboBox.getSelectedItem().toString().contains("Checking")) {
                                            transTypeId = DBConstants.CHECKING_DEBIT;
                                            transDescription = "Checking Debit";
                                        } else if (fromAccountJComboBox.getSelectedItem().toString().
                                                contains("Savings")) {
                                            transTypeId = DBConstants.SAVINGS_DEBIT;
                                            transDescription = "Savings Debit";
                                        } else if (fromAccountJComboBox.getSelectedItem().toString().
                                                contains("Loan")) {
                                            transTypeId = DBConstants.LOAN_DEBIT;
                                            transDescription = "Loan Debit";
                                        }
                                        SealedObject sealedAcctsData = new SealedObject(
                                                new Transaction(0, transTypeId, transDescription,
                                                "Test Transaction", Double.parseDouble(
                                                transactionAmountJTextField.getText()),
                                                Long.parseLong(temp[temp.length - 1].substring(1))), cipher);
                                        objOutStream.writeObject(sealedAcctsData);
                                        objOutStream.flush();

                                        SealedObject seleadSuccess = (SealedObject) objInStream.readObject();
                                        success = (Boolean) seleadSuccess.getObject(decipher);
                                        return null;
                                    }

                                    @Override
                                    public void done() {
                                        jProgressBar1.setVisible(false);
                                        if (success) {
                                            JOptionPane.showMessageDialog(thisJFrame,
                                                    "Transaction Successful",
                                                    "Success",
                                                    JOptionPane.INFORMATION_MESSAGE);
                                            needsDataReload = true;
                                        } else {
                                            JOptionPane.showMessageDialog(thisJFrame,
                                                    "Transaction Failure",
                                                    "Failure",
                                                    JOptionPane.ERROR_MESSAGE);
                                        }
                                    }
                                };
                                reloadData1.execute();
                            } else {
                                JOptionPane.showMessageDialog(thisJFrame,
                                        "Transaction Failure",
                                        "Failure",
                                        JOptionPane.ERROR_MESSAGE);
                            }
                        } else {
                            JOptionPane.showMessageDialog(thisJFrame,
                                    "Transaction Failure",
                                    "Failure",
                                    JOptionPane.ERROR_MESSAGE);
                        }
                        break;
                    case TRANSFER:
                        if (this.fromAccountJComboBox.getSelectedIndex() > 0
                                && this.toAccountJComboBox.getSelectedIndex() > 0 &&
                                this.fromAccountJComboBox.getSelectedIndex() != 
                                this.toAccountJComboBox.getSelectedIndex() &&
                                Double.parseDouble(transactionAmountJTextField.getText()) > 0) {
                            final String[] temp1 = fromAccountJComboBox.getSelectedItem().toString().split(" ");
                            final String[] temp2 = toAccountJComboBox.getSelectedItem().toString().split(" ");
                            AccountData fromAccount1 = 
                                    this.accountsData.get(this.fromAccountJComboBox.getSelectedIndex()-1);
                            
                            if (Double.parseDouble(transactionAmountJTextField.getText())
                                    < fromAccount1.getBalance()) {
                                this.objOutStream.writeObject(RequestType.TRANSFER);
                                this.objOutStream.flush();
                                SwingWorker<Void, Void> reloadData2 = new SwingWorker<Void, Void>() {

                                    private boolean success = false;

                                    @Override
                                    protected Void doInBackground() throws Exception {
                                        jProgressBar1.setVisible(true);
                                        int transTypeId = -1;
                                        String transDescription = "";
                                        if (toAccountJComboBox.getSelectedItem().toString().contains("Checking")) {
                                            transTypeId = DBConstants.CHECKING_CREDIT;
                                            transDescription = "Checking Credit";
                                        } else if (toAccountJComboBox.getSelectedItem().toString().
                                                contains("Savings")) {
                                            transTypeId = DBConstants.SAVINGS_CREDIT;
                                            transDescription = "Savings Credit";
                                        } else if (toAccountJComboBox.getSelectedItem().toString().
                                                contains("Loan")) {
                                            transTypeId = DBConstants.LOAN_CREDIT;
                                            transDescription = "Loan Credit";
                                        }
                                        int transTypeId1 = -1;
                                        String transDescription1 = "";
                                        if (fromAccountJComboBox.getSelectedItem().toString().contains("Checking")) {
                                            transTypeId1 = DBConstants.CHECKING_DEBIT;
                                            transDescription1 = "Checking Debit";
                                        } else if (fromAccountJComboBox.getSelectedItem().toString().
                                                contains("Savings")) {
                                            transTypeId1 = DBConstants.SAVINGS_DEBIT;
                                            transDescription1 = "Savings Debit";
                                        } else if (fromAccountJComboBox.getSelectedItem().toString().
                                                contains("Loan")) {
                                            transTypeId1 = DBConstants.LOAN_DEBIT;
                                            transDescription1 = "Loan Debit";
                                        }

                                        SealedObject sealedAcctsData = new SealedObject(
                                                new Transaction(0, transTypeId, transDescription,
                                                "Test Transaction", Double.parseDouble(transactionAmountJTextField.getText()),
                                                Long.parseLong(temp2[temp2.length - 1].substring(1))), cipher);
                                        objOutStream.writeObject(sealedAcctsData);
                                        objOutStream.flush();
                                        String[] temp1 = fromAccountJComboBox.getSelectedItem().toString().split(" ");
                                        SealedObject sealedAcctsData1 = new SealedObject(
                                                new Transaction(0, transTypeId1, transDescription1,
                                                "Test Transaction", Double.parseDouble(transactionAmountJTextField.getText()),
                                                Long.parseLong(temp1[temp1.length - 1].substring(1))), cipher);
                                        objOutStream.writeObject(sealedAcctsData1);
                                        objOutStream.flush();

                                        SealedObject seleadSuccess = (SealedObject) objInStream.readObject();
                                        success = (Boolean) seleadSuccess.getObject(decipher);
                                        return null;
                                    }

                                    @Override
                                    public void done() {
                                        jProgressBar1.setVisible(false);
                                        if (success) {
                                            JOptionPane.showMessageDialog(thisJFrame,
                                                    "Transaction Successful",
                                                    "Success",
                                                    JOptionPane.INFORMATION_MESSAGE);
                                            needsDataReload = true;
                                        } else {
                                            JOptionPane.showMessageDialog(thisJFrame,
                                                    "Transaction Failure",
                                                    "Failure",
                                                    JOptionPane.ERROR_MESSAGE);
                                        }
                                    }
                                };
                                reloadData2.execute();
                            } else {
                                JOptionPane.showMessageDialog(thisJFrame,
                                        "Transaction Failure",
                                        "Failure",
                                        JOptionPane.ERROR_MESSAGE);
                            }
                        } else {
                            JOptionPane.showMessageDialog(thisJFrame,
                                    "Transaction Failure",
                                    "Failure",
                                    JOptionPane.ERROR_MESSAGE);
                        }
                        break;
                }
            } catch (IOException e) {
                log.log(Level.SEVERE, "Failure in sendig RequestType Object", e);
            } catch (NumberFormatException e) {
                JOptionPane.showMessageDialog(thisJFrame,
                                    "Transaction Failure",
                                    "Failure",
                                    JOptionPane.ERROR_MESSAGE);
                log.log(Level.SEVERE, "Failure in sendig RequestType Object", e);
            }
        }
    }//GEN-LAST:event_confirmTransactionJButtonActionPerformed

    private void transactionTypeJComboBoxItemChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_transactionTypeJComboBoxItemChanged
        if (evt.getStateChange() == ItemEvent.SELECTED
                && this.transactionTypesComboBox.getSelectedIndex() > 0) {

            switch (TransactionType.get(
                    this.transactionTypesComboBox.getSelectedIndex())) {
                case DEPOSIT:
                    this.toAccountJComboBox.setEnabled(true);
                    this.fromAccountJComboBox.setEnabled(false);
                    this.confirmTransactionJButton.setEnabled(true);
                    break;
                case WITHDRAWL:
                    this.toAccountJComboBox.setEnabled(false);
                    this.fromAccountJComboBox.setEnabled(true);
                    this.confirmTransactionJButton.setEnabled(true);
                    break;
                case TRANSFER:
                    this.fromAccountJComboBox.setEnabled(true);
                    this.toAccountJComboBox.setEnabled(true);
                    this.confirmTransactionJButton.setEnabled(true);
                    break;
                default:
                    break;
            }

        } else if (evt.getStateChange() == ItemEvent.SELECTED
                && this.transactionTypesComboBox.getSelectedIndex() == 0) {
            this.fromAccountJComboBox.setEnabled(false);
            this.toAccountJComboBox.setEnabled(false);
            this.confirmTransactionJButton.setEnabled(false);
        }
    }//GEN-LAST:event_transactionTypeJComboBoxItemChanged

    public static void showFrame(final ClientLogin cLogIn, final java.net.Socket socket,
            final java.io.ObjectInputStream objInStream, final java.io.ObjectOutputStream objOutStream,
            final Cipher cipher, final Cipher decipher) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ClientAccounts.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ClientAccounts.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ClientAccounts.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ClientAccounts.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                try {
                    new ClientAccounts(cLogIn, socket, objInStream, objOutStream,
                            cipher, decipher).setVisible(true);
                } catch (BankingException e) {
                }
            }
        });
    }

//    public static ClientAccount hideFrame(final ClientLogin cLogIn, final java.net.Socket socket, final java.io.ObjectInputStream objInStream, final java.io.ObjectOutputStream objOutStream) {
//        /*
//         * Set the Nimbus look and feel
//         */
//        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
//        /*
//         * If Nimbus (introduced in Java SE 6) is not available, stay with the
//         * default look and feel. For details see
//         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
//         */
//        try {
//            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
//                if ("Nimbus".equals(info.getName())) {
//                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
//                    break;
//                }
//            }
//        } catch (ClassNotFoundException ex) {
//            java.util.logging.Logger.getLogger(ClientAccounts.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (InstantiationException ex) {
//            java.util.logging.Logger.getLogger(ClientAccounts.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (IllegalAccessException ex) {
//            java.util.logging.Logger.getLogger(ClientAccounts.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
//            java.util.logging.Logger.getLogger(ClientAccounts.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        }
//        //</editor-fold>
//
//        /*
//         * Create and display the form
//         */
//        java.awt.EventQueue.invokeLater(new Runnable() {
//
//            @Override
//            public void run() {
//                new ClientAccounts(cLogIn, socket, objInStream, objOutStream).setVisible(true);
//            }
//        });
//    }
    private void initAccountData(int selectedIndex) throws BankingException {
        this.accountNameJComboBox.removeAllItems();

        for (AccountData cur : this.accountsData) {
            this.accountNameJComboBox.addItem(MakeObj(cur.getAccountType() + " #"
                    + String.valueOf(cur.getAccountNum())));
        }

        this.accountNameJComboBox.setSelectedIndex(selectedIndex);

        this.curAcctDisplayed = this.accountsData.get(this.accountNameJComboBox.getSelectedIndex());

        loadTable();

    }

    private void loadTable() {
        double balance = this.curAcctDisplayed.getBalance();

        TableModel model = new TransactionTableModel(this.curAcctDisplayed.getTransactions().size() + 1);
        this.transactionsJTable.setModel(model);
        model.setValueAt(MakeObj("Current Balance"), 0, 0);
        model.setValueAt(MakeObj(String.format("$%1$.2f", balance)), 0, 3);


        for (int i = 0; i < this.curAcctDisplayed.getTransactions().size(); i++) {
            balance = loadRowInTable(model, i, balance);
        }
    }

    private double loadRowInTable(TableModel model, int i, double balance) {
        model.setValueAt(this.curAcctDisplayed.getTransactions().get(i).
                getTransactionDesc(), i + 1, 0);
        model.setValueAt(MakeObj(String.format("$%1$.2f", this.curAcctDisplayed.getTransactions().get(i).
                getTransactionValue())), i + 1,
                ((this.curAcctDisplayed.getTransactions().get(i).getTransactionTypeId() % 2) == 1)
                ? (2) : (1));
        balance = runningTotal(balance, i);
        model.setValueAt(MakeObj(String.format("$%1$.2f", balance)), i + 1, 3);
        return balance;
    }

    private double runningTotal(double balance, int i) {
        return balance += (((this.curAcctDisplayed.getTransactions().get(i).
                getTransactionTypeId() % 2) == 0)
                ? this.curAcctDisplayed.getTransactions().get(i).
                getTransactionValue() : (this.curAcctDisplayed.getTransactions().get(i).
                getTransactionValue() * -1));
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox accountNameJComboBox;
    private javax.swing.JScrollPane accountsJScrollPane;
    private javax.swing.JTabbedPane clientJTabbedPane;
    private javax.swing.JButton confirmTransactionJButton;
    private javax.swing.JComboBox fromAccountJComboBox;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JProgressBar jProgressBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane optionsJScrollPane;
    private javax.swing.JComboBox toAccountJComboBox;
    private javax.swing.JLabel transactionAmountJLabel;
    private javax.swing.JTextField transactionAmountJTextField;
    private javax.swing.JComboBox transactionTypesComboBox;
    private javax.swing.JTable transactionsJTable;
    // End of variables declaration//GEN-END:variables
    //Non-Design variables declaration
    private static final Logger log = Logger.getLogger(ClientLogin.class.getName());
    private java.net.Socket socket;
    private java.io.ObjectInputStream objInStream;
    private java.io.ObjectOutputStream objOutStream;
    private Cipher cipher;
    private Cipher decipher;
    private ClientLogin cLogIn;
    private List<AccountData> accountsData;
    private AccountData curAcctDisplayed;

    private Object MakeObj(final String item) {
        return new Object() {

            @Override
            public String toString() {
                return item;
            }
        };
    }

    private enum TransactionType {
        //Enum Values

        DEPOSIT(1),
        WITHDRAWL(2),
        TRANSFER(3);
        //Static Members
        private static final Map<Integer, TransactionType> lookup = new HashMap<Integer, TransactionType>();
        //Instance Members
        private int type;

        //Static Methods
        static {
            for (TransactionType s : EnumSet.allOf(TransactionType.class)) {
                lookup.put(s.getType(), s);
            }
        }

        public static TransactionType get(int type) {
            return lookup.get(type);
        }

        //Instance Methods
        private TransactionType(int type) {
            this.type = type;
        }

        public int getType() {
            return type;
        }
    }
    private static boolean needsDataReload;
    //End Non-Design variables declaration 
}
